﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;

namespace Aiss.Sync
{
    [Serializable]
    public class Tables:Csla.BusinessListBase<Tables,Table>
    {
        private Tables()
        {
            //IsReadOnly = false;
        }

        public static Tables GetTables()
        {
            return Csla.DataPortal.Fetch<Tables>(new Criteria());
        }

        private class Criteria
        {
        }

        protected override void DataPortal_Fetch(object criteria)
        {
           // IsReadOnly = false;
            RaiseListChangedEvents = false;
            using (SqlConnection cn = new SqlConnection(Aiss.Sync.Settings.ConnStringMain))
            {
                cn.Open();

                SqlCommand cm = cn.CreateCommand();
                cm.CommandType = CommandType.Text;
                cm.CommandText = @"SELECT object_id, name FROM sys.objects where type = N'U' ORDER BY name

                                    SELECT name,object_id,is_nullable FROM sys.columns 
                                    where sys.columns.object_id in (SELECT object_id FROM sys.objects 
                                    where type = N'U' )";

                SafeDataReader dr = new SafeDataReader(cm.ExecuteReader());
                while (dr.Read())
                {
                    this.Add(Table.GetTable(dr));
                }

                dr.NextResult();

                while (dr.Read())
                {
                    var tab = (from i in this where i.Object_id == dr.GetInt32(1) select i).FirstOrDefault();
                    tab.Columns.Add(Aiss.Sync.Column.GetColumn(dr));
                }

            }
            //IsReadOnly = true;
            RaiseListChangedEvents = true;
        }
    }
}
